package com.jy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jy.common.enums.ResponseWrapper;
import com.jy.common.model.user.param.HandupOrHandDownParam;
import com.jy.entity.Dynamic;
import com.jy.entity.ThumbsUp;
import com.jy.mapper.DynamicMapper;
import com.jy.mapper.ThumbsUpMapper;
import com.jy.service.ThumbsUpService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 点赞表（用户点赞，点赞类型：帖子，动态，笔记......） 服务实现类
 * </p>
 *
 * @author fzg
 * @since 2024-11-14
 */
@Service
public class ThumbsUpServiceImpl extends ServiceImpl<ThumbsUpMapper, ThumbsUp> implements ThumbsUpService {

    @Autowired
    private ThumbsUpMapper thumbsUpMapper;

    @Autowired
    private DynamicMapper dynamicMapper;

    @Override
    public ResponseWrapper handUpOrHandDown(Integer userAidByToken, HandupOrHandDownParam param) {

        ThumbsUp thumbsUp = thumbsUpMapper.selectOne(new LambdaQueryWrapper<ThumbsUp>()
                .eq(ThumbsUp::getThumbsUpUserAid, userAidByToken)
                .eq(ThumbsUp::getThumbsUpedAid, param.getDynamicAid())
                .eq(ThumbsUp::getType, param.getType())
        );
        Dynamic dynamic = dynamicMapper.selectById(param.getDynamicAid());
        if (thumbsUp == null) {
            // 如果没查询到，说明没有点赞（去点赞，添加一条点赞记录）
            thumbsUpMapper.insert(new ThumbsUp(){{
                setHandColor("red");
                setHandType("heart-filled");
                setThumbsUpUserAid(userAidByToken);
                setThumbsUpedAid(param.getDynamicAid());
                setType(param.getType());
            }});
            // 动态表点赞数量+1
            dynamic.setDianZanNum(dynamic.getDianZanNum()+1);
            dynamicMapper.updateById(dynamic);
            return ResponseWrapper.markSuccess();
        }else {
            // 查询到了说明已经点赞（去删除记录，取消点赞）
            thumbsUpMapper.deleteById(thumbsUp);
            // 动态表点赞数量-1
            dynamic.setDianZanNum(dynamic.getDianZanNum()-1);
            dynamicMapper.updateById(dynamic);
            return ResponseWrapper.markSuccess();
        }
    }
}
